package com.terrier.ui.effects
{
	import com.terrier.ui.events.WxEffectEvent;
	
	import flash.display.DisplayObject;
	
	public class WxSequentialEffect extends WxAbstractEffect
	{		
		private var _arrEffects:Array;
		private var _currRunningEffectIndex:int = -1;
		
		public function WxSequentialEffect(arrEffects:Array, target:DisplayObject = null,
										   startEventParams:Object = null,
										   updateEventParams:Object = null,
										   stopEventParams:Object = null)
		{
			this._arrEffects = arrEffects;
			if(this._arrEffects.length > 0)
			{
				this._currRunningEffectIndex = 0;
			}
			super(target, 0.0, startEventParams, updateEventParams, stopEventParams);
			for each(var effect:IWxAbstractEffect in this._arrEffects)
			{
				this.runTime += effect.runTime;
			}
		}
		
		protected override function initialize():void
		{
			if(this._arrEffects == null || this._currRunningEffectIndex == -1)
			{
				throw new Error("There are no valid effects registered under sequential effects");
			}
		}
		
		public override function start():void
		{
			super.start();
			
			var currEffect:WxAbstractEffect = this._arrEffects[this._currRunningEffectIndex];
			currEffect.addEventListener(WxEffectEvent.EFFECT_STOP, startNextAnimation);
			currEffect.start();	
		}
		
		private function startNextAnimation(event:WxEffectEvent):void
		{
			if(this._currRunningEffectIndex == this._arrEffects.length - 1)
			{
				this.stop();
				return;
			}
			
			++this._currRunningEffectIndex;
			var currEffect:WxAbstractEffect = this._arrEffects[this._currRunningEffectIndex];
			currEffect.addEventListener(WxEffectEvent.EFFECT_STOP, startNextAnimation);
			currEffect.start();
		}
		
		public override function stop():void
		{
			for each(var effect:IWxAbstractEffect in this._arrEffects)
			{
				if(effect.running)
				{
					effect.stop();
				}
			}
			super.stop();
		}
		
		public function get arrEffects():Array
		{
			return this._arrEffects;
		}
		
		public override function set target(value:DisplayObject):void
		{
			super.target = value;
			for each(var effect:WxAbstractEffect in this._arrEffects)
			{
				effect.target = value;
			}
		}
		
		public override function clone():IWxAbstractEffect
		{
			var newEffect:WxSequentialEffect = new WxSequentialEffect(
				this.arrEffects, 
				this.target,
				this.startEventParams,
				this.updateEventParams, 
				this.stopEventParams);
			return newEffect;
		}
	}
}